package com.hzjy.api.service.impl;

import com.hzjy.common.core.redis.RedisCache;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.JSON;
import com.hzjy.common.utils.http.HttpUtils;
import com.hzjy.common.utils.sign.Md5Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class SmsServiceImpl {
    @Value("${SMS.sms_user}")
    private String sms_user;
    @Value("${SMS.sms_key}")
    private String sms_key;
    @Value("${SMS.templateId}")
    private String templateId;
    @Value("${SMS.url}")
    private String url;
    @Value("${SMS.expireTime}")
    private Integer expireTime;

    @Autowired
    private RedisCache redisCache;

    /**
     * sendCloud 发送验证码
     * @param phone 手机号
     * @param code 验证码
     */
    public void createSignature(String phone,String code){
        String vars="{\"code\":\""+code+"\"}";
        String param_str="phone="+phone+"&"+"smsUser="+sms_user+"&"+"templateId="+templateId+"&"+"vars="+vars;

        String sign_str=sms_key+"&"+param_str+"&"+sms_key;
        String signature= Md5Utils.hash(sign_str);
        String param="smsUser="+sms_user+"&templateId="+templateId+"&phone="+phone+"&signature="+signature+"&vars="+vars;
        String responseString=HttpUtils.sendGet(url,param);
        JSONObject object = JSON.parseObject(responseString);
        if(object.getIntValue("statusCode")==200){
            System.out.println("成功给手机号:"+phone+"发送验证码:"+code);
            redisCache.setCacheObject(phone,code,expireTime, TimeUnit.MINUTES); //将验证码缓存
        }
    }
}
